#include "../StdAfx.h"
#include "ProcessMessage.h"
#include "../MainManager.h"
#include "../Logger.h"
#include "RawData.h"
#include "../Messages/Hello.pb.h"
#include "../Messages/Car.pb.h"
#include <map>
#include <boost/foreach.hpp>

namespace DerbyServ
{

void ProcessHelloMessage(MainManager & mgr, RawType & raw, int cId)
{
	{
		Messages::Hello hello;
		hello.ParseFromArray(raw.data(), raw.size());
		LOGD("From client # " << cId << ": " << hello.text());
	}
	//TODO schedule
	{
		Messages::Hello hello;
		hello.set_clientid(cId);
		hello.set_text("Hello, client!!");
		mgr.GetSocketManager().Send(hello, Messages::MESSAGE_HELLO, cId);
	}
}

void ProcessCarMessage(MainManager & mgr, RawType & raw, int connectionId)
{
	Messages::Car car;
	car.ParseFromArray(raw.data(), raw.size());

	//TODO schedule following messages
	{
		LOGD("car.clientid() = " << car.clientid() << ", connectionId = " << connectionId);
		BOOST_ASSERT(car.clientid() == connectionId);
		std::vector<int> cnIds = mgr.GetSocketManager().GetConnectionIds();
		for(int i = 0; i < cnIds.size(); ++i)
		{
			int cnId = cnIds[i];
			if (cnId != connectionId)
			{
				LOGD("Info about the car of the client " << car.clientid() << " is sending to the client " << cnId);
				mgr.GetSocketManager().Send(car, Messages::MESSAGE_CAR, cnId);
			}
		}
	}
}

////////////////

std::map<enum Messages::MessageTypes, ProcessMessage> RegisterMessageProcessors()
{
	std::map<enum Messages::MessageTypes, ProcessMessage> messageProcessors;
	messageProcessors[Messages::MESSAGE_HELLO] = &ProcessHelloMessage;
	messageProcessors[Messages::MESSAGE_CAR] = &ProcessCarMessage;

	return messageProcessors;
}


} // namespace
